# import nmap
# scanner = nmap.PortScanner()
# scanner.scan('192.168.1.1', '1-1024')
# print(scanner.all_hosts())

import socket
import concurrent.futures


def check_port(ip, port, timeout=1.0):
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.settimeout(timeout)
            return port if s.connect_ex((ip, port)) == 0 else None
    except:
        return None


def scan_ports(ip, start_port, end_port, max_threads=100):
    open_ports = []
    with concurrent.futures.ThreadPoolExecutor(max_workers=max_threads) as executor:
        futures = {executor.submit(check_port, ip, port): port for port in range(start_port, end_port + 1)}
        for future in concurrent.futures.as_completed(futures):
            if (port := future.result()):
                print(f"Port {port}: OPEN")
                open_ports.append(port)
    return sorted(open_ports)


if __name__ == "__main__":
    # target_ip = "192.168.1.1"
    target_ip = "ip172-19-0-14-d2lhbkgi7hog00dla240.direct.labs.play-with-k8s.com"
    start_port = 1024
    end_port = 65535

    print(f"Scanning {target_ip} (ports {start_port}-{end_port})...")
    open_ports = scan_ports(target_ip, start_port, end_port)

    print("\nOpen ports:", open_ports or "None")